package main

import (
	"os"

	"gopkg.in/yaml.v3"
)

type Config struct {
	Log     *LogConfig      `yaml:"log"`
	Http    *HttpConfig     `yaml:"http"`
	Oss     []*OssConfig    `yaml:"oss"`
	Servers []*ServerConfig `yaml:"servers"`
}

type LogConfig struct {
	Path       string `yaml:"path"`   // - 是 stdout
	Level      string `yaml:"level"`  // debug/info/warn/error，默认 info
	Format     string `yaml:"format"` // text/json，默认 text
	MaxSize    int    `yaml:"maxSize"`
	MaxAge     int    `yaml:"maxAge"`
	MaxBackups int    `yaml:"maxBackups"`
	LocalTime  bool   `yaml:"localTime"`
	Compress   bool   `yaml:"compress"`
}

type HttpCertConfig struct {
	Name string `yaml:"name"`
	Cert string `yaml:"cert"`
	Key  string `yaml:"key"`
}

type HttpConfig struct {
	Listen    string            `yaml:"listen"`
	ListenTLS string            `yaml:"listenTls"`
	Certs     []*HttpCertConfig `yaml:"certs"`
}

type OssProviderConfig struct {
	Kind            string `yaml:"kind"`
	AccessKeyID     string `yaml:"accessKeyId"`
	AccessKeySecret string `yaml:"accessKeySecret"`
	SecurityToken   string `yaml:"securityToken"`
	RamRole         string `yaml:"ramRole"`
	Command         string `yaml:"command"`
}

type OssConfig struct {
	Name                string             `yaml:"name"`
	Provider            *OssProviderConfig `yaml:"provider"`
	Region              string             `yaml:"region"`
	DisableSsl          bool               `yaml:"disableSsl"`
	UseInternalEndpoint bool               `yaml:"useInternalEndpoint"`
}

type ServerConfig struct {
	Host           string  `yaml:"host"`
	Cert           string  `yaml:"cert"`
	SslRedirect    bool    `yaml:"sslRedirect"`
	Oss            string  `yaml:"oss"`
	Bucket         string  `yaml:"bucket"`
	Prefix         string  `yaml:"prefix"`
	Index          string  `yaml:"index"`
	NotFound       string  `yaml:"notFound"`
	RewriteToIndex *string `yaml:"rewriteToIndex"`
}

func loadConfig(fname string) (*Config, error) {
	data, err := os.ReadFile(fname)
	if err != nil {
		return nil, err
	}

	var c Config
	err = yaml.Unmarshal(data, &c)
	if err != nil {
		return nil, err
	}

	return &c, nil
}
